<template>
  <view class="container">
    <!-- 商品轮播图 -->
    <swiper class="banner" circular autoplay interval="3000" duration="500">
      <swiper-item v-for="(item, index) in goodsInfo.bannerList" :key="index">
        <image class="banner-image" :src="item.url" mode="aspectFill"></image>
      </swiper-item>
    </swiper>
    
    <!-- 商品信息 -->
    <view class="goods-info">
      <view class="price-box">
        <text class="price">¥{{goodsInfo.price}}</text>
        <text class="unit">/{{goodsInfo.unit}}</text>
      </view>
      <view class="name-box">
        <text class="name">{{goodsInfo.name}}</text>
        <text class="desc">{{goodsInfo.desc}}</text>
      </view>
      <view class="sales-box">
        <text class="sales">已售 {{goodsInfo.sold}}件</text>
      </view>
    </view>
    
    <!-- 商品参数 -->
    <view class="goods-params">
      <view class="param-item">
        <text class="label">产地</text>
        <text class="value">{{goodsInfo.origin}}</text>
      </view>
      <view class="param-item" v-for="(spec, index) in goodsInfo.specifications" :key="index">
        <text class="label">{{spec.name}}</text>
        <text class="value">{{spec.values.map(v => v.value).join(' / ')}}</text>
      </view>
      <view class="param-item">
        <text class="label">保质期</text>
        <text class="value">{{goodsInfo.shelfLife+' / '+getStorageLabel(goodsInfo.storage)}}</text>
      </view>
      <view class="param-item">
        <text class="label">储存方式</text>
        <text class="value">{{getStorageRemark(goodsInfo.storage)}}</text>
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="goods-detail">
      <view class="section-title">商品详情</view>
      <rich-text :nodes="goodsInfo.detail"></rich-text>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="action-icons">
        <view class="icon-item" @tap="goHome">
          <text class="icon">🏠</text>
          <text>首页</text>
        </view>
        <view class="icon-item">
          <text class="icon">💬</text>
          <text>客服</text>
        </view>
        <view class="icon-item" @tap="goCart">
          <text class="icon">🛒</text>
          <text>购物车</text>
          <text class="cart-num" v-if="cartNum > 0">{{cartNum}}</text>
        </view>
      </view>
      <view class="action-btns">
        <button class="add-cart" @click="showSkuPopup('add')">加入购物车</button>
        <button class="buy-now" @click="showSkuPopup('buy')">立即购买</button>
      </view>
    </view>
    
    <!-- SKU选择弹窗 -->
    <uni-popup ref="skuPopup" type="bottom">
      <view class="sku-popup">
        <view class="popup-header">
          <image class="selected-sku-image" :src="selectedSku.image || goodsInfo.bannerList[0]?.url" mode="aspectFill"></image>
          <view class="selected-info">
            <text class="price">¥{{currentPrice}}</text>
            <text class="stock">库存 {{selectedSku.stock || goodsInfo.stock}}件</text>
            <text class="selected-text">已选：{{selectedSpecs.map(s => s.value).join(' ')}}</text>
          </view>
          <text class="close-btn" @click="closeSkuPopup">×</text>
        </view>
        
        <scroll-view class="popup-content" scroll-y>
          <view 
            class="sku-group" 
            v-for="(group, groupIndex) in goodsInfo.skuGroups" 
            :key="group.title"
          >
            <text class="group-title">{{group.title}}</text>
            <view class="sku-list">
              <view 
                class="sku-item" 
                v-for="spec in goodsInfo.specValues.find(sv => sv.title === group.title)?.values" 
                :key="spec"
                :class="{ 
                  active: isSpecSelected(groupIndex, spec),
                  disabled: isSpecDisabled(groupIndex, spec)
                }"
                @click="!isSpecDisabled(groupIndex, spec) && selectSpec(groupIndex, spec)"
              >
                <text class="sku-name">{{spec}}</text>
              </view>
            </view>
          </view>
          
          <view class="number-picker">
            <text class="group-title">购买数量</text>
            <view class="number-box">
              <uni-number-box 
                v-model="buyNum"
                :min="1"
                :max="maxBuyNum"
              ></uni-number-box>
            </view>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmSku">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { systemApi,farmerApi,userApi } from '@/api'
import { useDict, getDictLabel, getDictRemark } from '@/utils/dict'
import { useCartStore } from '@/store'

export default {
  data() {
    return {
      goodsId: '',
      goodsInfo: {
        id: '',
        name: '',
        desc: '',
        price: '',
        unit: '',
        sold: 0,
        origin: '',
        spec: '',
        shelfLife: '',
        storage: '',
        stock: 0,
        detail: '',
        bannerList: [],
        skuGroups: [],
        specValues: [],
        skuList: [],
        specifications: []
      },
      cartNum: 0,
      buyNum: 1,
      maxBuyNum: 99,
      selectedSpecs: [],
      selectedSku: {},
      originalBannerList: [],
      // 字典数据
      dict: {},
      storageOptions: null,
      actionType: 'add'
    }
  },
  computed: {
    // 计算当前选中SKU的总价
    currentPrice() {
      const basePrice = this.selectedSku.price || this.goodsInfo.price
      return (basePrice * this.buyNum).toFixed(2)
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.goodsId = options.id
      // 先加载字典数据
      await this.loadDict()
      // 再加载商品详情
      await this.loadGoodsDetail()
      // 获取购物车数量
      this.updateCartNum()
    }
  },
  methods: {

    // 获取地区名称
    async getRegionNames(codes) {
      try {
        const result = await systemApi.areaCode()
        if (!Array.isArray(codes) || codes.length === 0) return ''
        
        // 递归查找地区
        const findRegion = (list, id) => {
          for (const item of list) {
            if (item.areaId === id) {
              return item
            }
            if (item.children && item.children.length > 0) {
              const found = findRegion(item.children, id)
              if (found) return found
            }
          }
          return null
        }
        
        // 获取每个编码对应的地区名称
        const names = codes.map(code => {
          const region = findRegion(result, code)
          return region ? region.areaName : ''
        }).filter(Boolean)
        
        return names.join(' ')
      } catch (error) {
        console.error('获取地区名称失败:', error)
        return ''
      }
    },
    // 加载字典数据
    async loadDict() {
      try {
        this.dict = await useDict('product_storage_condition')
        this.storageOptions = this.dict.product_storage_condition
      } catch (error) {
        console.error('加载字典数据失败:', error)
      }
    },
    
    // 获取存储条件的标签
    getStorageLabel(value) {
      return getDictLabel(this.storageOptions, value)
    },
    getStorageRemark(value) {
      return getDictRemark(this.storageOptions, value)
    },
    
    async loadGoodsDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        

        // 获取商品详情
        const result = await farmerApi.getGoodsDetail(this.goodsId)
        
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 转换规格数据结构
        const skuGroups = result.specifications.map(spec => ({
          title: spec.name
        }))
        
        // 转换规格值列表
        const specValues = result.specifications.map(spec => ({
          title: spec.name,
          values: spec.values.map(v => v.value)
        }))
        
        // 转换SKU列表
        const skuList = result.skus.map(sku => ({
          id: sku.id,
          specs: sku.specs.map(spec => ({
            name: spec.name,
            value: spec.value
          })),
          price: sku.price,
          stock: sku.stock,
          image: sku.image || result.mainImage
        }))
        
        // 获取地区名称
        const originNames = await this.getRegionNames(result.origin)
        
        this.goodsInfo = {
          ...this.goodsInfo,
          id: result.id,
          name: result.productsName,
          desc: '', 
          price: skuList[0]?.price || '0.00',
          unit: '份',
          sold: 0,
          origin: originNames || '暂无产地信息',
          specifications: result.specifications,
          spec: '',
          shelfLife: `${result.shelfLife}天`,
          storage: result.storageCondition,
          stock: skuList.reduce((total, sku) => total + sku.stock, 0),
          detail: result.description,
          // 合并主图和图片列表
          bannerList: [
            { url: result.mainImage },
            ...(result.images?.map(img => ({ url: img.url })) || [])
          ],
          skuGroups,
          specValues,
          skuList
        }

      
        // const remark = getDictRemark(this.storageOptions, value)
        //console.log(getDictLabel(this.storageOptions, result.storageCondition) );
        
      } catch (error) {
        console.error('获取商品详情失败:', error)
        uni.showToast({
          title: '获取商品详情失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 选择规格
    selectSpec(groupIndex, spec) {
      const group = this.goodsInfo.skuGroups[groupIndex]
      
      // 更新选中的规格
      const specIndex = this.selectedSpecs.findIndex(item => item.name === group.title)
      if (specIndex > -1) {
        // 如果已经选择过该组的规格，更新它
        this.selectedSpecs.splice(specIndex, 1, { name: group.title, value: spec })
      } else {
        // 如果是新选择的规格组，添加它
        this.selectedSpecs.push({ name: group.title, value: spec })
      }
      
      // 查找匹配的SKU
      const matchedSku = this.findMatchedSku()
      
      // 更新选中的SKU和图片
      if (matchedSku) {
        this.selectedSku = matchedSku
        if (matchedSku.image) {
          this.goodsInfo.bannerList = [{ url: matchedSku.image }]
        }
      }
    },
    
    // 查找匹配的SKU
    findMatchedSku() {
      if (this.selectedSpecs.length === 0) return null
      
      return this.goodsInfo.skuList.find(sku => {
        // 所有已选规格都要匹配
        return this.selectedSpecs.every(selectedSpec => {
          return sku.specs.some(skuSpec => 
            skuSpec.name === selectedSpec.name && 
            skuSpec.value === selectedSpec.value
          )
        })
      })
    },
    
    // 判断规格是否可选
    isSpecDisabled(groupIndex, spec) {
      const group = this.goodsInfo.skuGroups[groupIndex]
      
      // 如果只选择了当前规格组或未选择任何规格，则所有规格都可选
      if (this.selectedSpecs.length === 0 || 
         (this.selectedSpecs.length === 1 && this.selectedSpecs[0].name === group.title)) {
        return false
      }
      
      // 复制当前已选规格
      const currentSpecs = [...this.selectedSpecs]
      
      // 移除当前规格组的选择（如果有）
      const currentSpecIndex = currentSpecs.findIndex(item => item.name === group.title)
      if (currentSpecIndex > -1) {
        currentSpecs.splice(currentSpecIndex, 1)
      }
      
      // 添加当前正在判断的规格
      currentSpecs.push({ name: group.title, value: spec })
      
      // 检查是否存在包含当前规格组合的有库存SKU
      return !this.goodsInfo.skuList.some(sku => {
        return currentSpecs.every(spec => 
          sku.specs.some(skuSpec => 
            skuSpec.name === spec.name && 
            skuSpec.value === spec.value
          )
        ) && sku.stock > 0
      })
    },
    
    // 判断规格是否选中
    isSpecSelected(groupIndex, spec) {
      const group = this.goodsInfo.skuGroups[groupIndex]
      return this.selectedSpecs.some(item => 
        item.name === group.title && item.value === spec
      )
    },
    
    // 跳转到首页
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    
    // 跳转到购物车
    goCart() {
      uni.switchTab({
        url: '/pages/cart/index'
      })
    },
    
    // 显示规格选择弹窗
    showSkuPopup(action = 'add') {
      this.actionType = action // 记录当前操作类型：add-加入购物车，buy-立即购买
      this.originalBannerList = [...this.goodsInfo.bannerList]
      this.selectedSpecs = []
      this.selectedSku = {}
      this.$refs.skuPopup.open()
    },
    
    // 关闭规格选择弹窗
    closeSkuPopup() {
      this.$refs.skuPopup.close()
      this.goodsInfo.bannerList = this.originalBannerList
    },
    
    // 确认SKU选择
    confirmSku() {
      if (!this.selectedSku.id) {
        uni.showToast({
          title: '请选择完整规格',
          icon: 'none'
        })
        return
      }
      
      // 根据不同的操作类型调用不同的方法
      if (this.actionType === 'add') {
        this.addToCart()
      } else if (this.actionType === 'buy') {
        this.buyNow()
      }
      
      this.closeSkuPopup()
    },
    
    // 更新购物车数量
    updateCartNum() {
      const cartStore = useCartStore()
      this.cartNum = cartStore.getTotalCount
    },
    
    // 加入购物车
    async addToCart() {
      try {
        const cartStore = useCartStore()
        const cartItem = {
          productId: this.goodsId,
          skuId: this.selectedSku.id,
          price: this.selectedSku.price,
          quantity: this.buyNum,
          specs: this.selectedSpecs,
          name: this.goodsInfo.name,
          image: this.selectedSku.image || this.goodsInfo.bannerList[0]?.url
        }
        
        // 先更新本地购物车
        cartStore.addToCart(cartItem)
        
        // 再同步到服务器
        const params = {
          productId: this.goodsId,
          productName: this.goodsInfo.name,
          productImage: this.selectedSku.image || this.goodsInfo.bannerList[0]?.url,
          skuId: this.selectedSku.id,
          priceSnapshot: this.selectedSku.price,
          specSnapshot: JSON.stringify(this.selectedSpecs),
          quantity: this.buyNum
        }
        await userApi.addCart(params)
        
        // 更新购物车数量显示
        this.updateCartNum()
        
        uni.showToast({
          title: '加入购物车成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('加入购物车失败:', error)
        uni.showToast({
          title: '加入购物车失败',
          icon: 'none'
        })
      }
    },
    
    // 立即购买
    buyNow() {
      // 验证是否已选择SKU
      if (!this.selectedSku || !this.selectedSku.id) {
        uni.showToast({
          title: '请选择商品规格',
          icon: 'none'
        })
        return
      }

      // 构造规格文本
      const specValues = []
      this.goodsInfo.specifications.forEach((spec, index) => {
        if (this.selectedSpecs[index]) {
          specValues.push(this.selectedSpecs[index].value)
        }
      })
      const specText = specValues.join('/')

      // 构造订单数据（使用数组格式）
      const orderData = [{
        productId: this.goodsInfo.id,
        productName: this.goodsInfo.name,
        skuId: this.selectedSku.id,
        quantity: this.buyNum,
        price: this.selectedSku.price,
        specifications: specText,
        image: this.selectedSku.image || this.goodsInfo.bannerList[0]?.url
      }]

      // 跳转到确认订单页
      uni.navigateTo({
        url: `/pages/order/confirm/index?orderData=${encodeURIComponent(JSON.stringify(orderData))}&type=detail`
      })
    },
    
    // 获取字典分类的类名
    getDictClass(dict, value) {
      const dictItem = dict[value]
      if (dictItem) {
        return dictItem.class
      }
      return 'default'
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.banner {
  width: 100%;
  height: 750rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.goods-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.price-box {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
}

.price {
  font-size: 48rpx;
  color: var(--price-color);
  font-weight: bold;
}

.unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.name-box {
  margin-bottom: 16rpx;
}

.name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.desc {
  font-size: 26rpx;
  color: #666;
  display: block;
}

.sales-box {
  font-size: 24rpx;
  color: #999;
}

.goods-params {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.param-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.param-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.goods-detail {
  background: #fff;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background: var(--primary-color);
  border-radius: 3rpx;
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  padding: 0 20rpx;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-icons {
  display: flex;
  align-items: center;
}

.icon-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40rpx;
  font-size: 20rpx;
  color: #666;
}

.icon {
  font-size: 40rpx;
  margin-bottom: 4rpx;
}

.cart-num {
  position: absolute;
  top: -10rpx;
  right: -16rpx;
  min-width: 32rpx;
  height: 32rpx;
  padding: 0 8rpx;
  background: #ff4d4f;
  border-radius: 16rpx;
  color: #fff;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btns {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.add-cart,
.buy-now {
  width: 180rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  border-radius: 36rpx;
  font-size: 28rpx;
  margin-left: 20rpx;
}

.add-cart {
  background: var(--light-yellow);
  color: var(--secondary-color);
  border: 1rpx solid var(--secondary-color);
}

.buy-now {
  background: var(--primary-color);
  color: #fff;
}

/* SKU弹窗样式 */
.sku-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  padding: 32rpx;
  position: relative;
}

.selected-sku-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
}

.selected-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10rpx 0;
}

.selected-info .price {
  font-size: 36rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.selected-info .stock {
  font-size: 24rpx;
  color: #999;
}

.selected-info .selected-text {
  font-size: 26rpx;
  color: #666;
}

.close-btn {
  position: absolute;
  right: 24rpx;
  top: 24rpx;
  font-size: 44rpx;
  color: #999;
  padding: 10rpx;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 32rpx;
}

.sku-group {
  padding: 24rpx 0;
  border-top: 1rpx solid #f5f5f5;
}

.sku-group:first-child {
  border-top: none;
}

.group-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
  font-weight: 500;
}

.sku-list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -8rpx 16rpx;
}

.sku-item {
  min-width: 120rpx;
  height: 60rpx;
  margin: 0 8rpx 16rpx;
  background: #fff;
  border: 1rpx solid #ddd;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sku-item.active {
  background: #e8f5e9;
  border-color: #4caf50;
  color: #4caf50;
}

.sku-item.disabled {
  background: #f5f5f5;
  border-color: #eee;
  color: #999;
  cursor: not-allowed;
}

.sku-name {
  font-size: 26rpx;
  padding: 0 20rpx;
}

.number-picker {
  padding: 24rpx 0;
  border-top: 1rpx solid #f5f5f5;
}

.number-box {
  display: flex;
  align-items: center;
}

.popup-footer {
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f5f5f5;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #4caf50, #45a049);
  color: #fff;
  font-size: 30rpx;
  border-radius: 40rpx;
  font-weight: 500;
  border: none;
}

/* 商品状态样式 */
.value.default {
  color: #909399;
}
.value.success {
  color: #67C23A;
}
.value.warning {
  color: #E6A23C;
}
.value.danger {
  color: #F56C6C;
}
</style> 